using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Configuration.Assemblies;

namespace SCRUM.Core.Configuration
{
    /// <summary>
    /// Configuration manager
    /// </summary>
    public class ConfigManager
    {
        /// <summary>
        /// Name of the XML file to save/load
        /// </summary>
        public static string fileName = AppDomain.CurrentDomain.BaseDirectory + System.Configuration.ConfigurationManager.AppSettings["configFilePath"].ToString().TrimStart('\\');
        
        /// <summary>
        /// Initializes the <see cref="ConfigManager"/> class.
        /// </summary>
        static ConfigManager()
        {
            CurrentConfig = Load();
        }

        /// <summary>
        /// Gets or sets the current config.
        /// </summary>
        /// <value>The current config.</value>
        public static Config CurrentConfig { get; set; }

        /// <summary>
        /// Saves the specified file name.
        /// </summary>
        public static void Save()
        {
            XmlSerializer ser = new XmlSerializer(typeof(Config));
            FileStream file = null;
            try
            {
                file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
                ser.Serialize(file, CurrentConfig);
            }
            finally
            {
                if (file != null)
                {
                    file.Close();
                }
            }
        }

        /// <summary>
        /// Loads the specified file name.
        /// </summary>
        /// <returns>New Config loaded from file</returns>
        private static Config Load()
        {
            XmlSerializer ser = new XmlSerializer(typeof(Config));
            FileStream file = null;
            try
            {
                file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                return ser.Deserialize(file) as Config;
            }
            finally
            {
                if (file != null)
                {
                    file.Close();
                }
            }
        }   
    }
}
